package cn.tedu.weibo2.controller;

import cn.tedu.weibo2.mapper.UserMapper;
import cn.tedu.weibo2.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    UserMapper mapper;

    @RequestMapping("/check")
    public int check(String username){
        User user = mapper.selectByUsername(username);
        if (user == null){
            return 1;
        }
        return 2;
    }

    @RequestMapping("/reg")
    public int insert(User user){
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null){
            return 2;
        }
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u == null){
            return 2;
        }
        if (u.getPassword().equals(user.getPassword())){
            //把当前登录成功的用户信息保存到Session对象中
            session.setAttribute("u",u);
            return 1;
        }
        return 3;
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("u");
    }


    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User) session.getAttribute("u");
    }

}
